﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FluentValidation;
using GalaSoft.MvvmLight.Command;
using SilverlightDemo.MonHocServiceReference;
using SilverlightDemo.Validators;
using FluentValidation;
using System.Linq;
using System.Threading;
using System.ServiceModel;
using System.Windows.Browser;
namespace SilverlightDemo.ViewModels
{
    public class MonHocViewModel:ViewModelBase
    {
        private readonly AbstractValidator<MonHoc> validator = new MonHocValidator();   
        private MonHocServiceClient monhocclient = new MonHocServiceClient();
        private bool IsInsert=false;
        private bool IsSaved = true;
        bool IsNew = false;
        #region Event
        private IList<MonHoc> monhocs=new List<MonHoc>();
        public void LoadingRow(Object sender, DataGridRowEventArgs e)
        {
            DataGrid dg = (DataGrid)sender;
            int index = e.Row.GetIndex();
            TextBlock cell = (TextBlock)dg.Columns[0].GetCellContent(e.Row);
            cell.Text = index + "";          
        }
        bool hang = false;
     
        public void KeyDown(object sender, KeyEventArgs e)
        {            
           DataGrid dg= ((DataGrid)sender);
            
           if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
           {
               //if (e.Key == Key.D6) RefreshMonHoc();
               //else
                   if (e.Key == Key.D1||e.Key==Key.NumPad1)
                   {
                       //Them hang moi                  
                       MonHoc mh = new MonHoc();
                       Monhocs.Insert(0, mh);
                       newmonhoc = Monhocs.First();
                       Currentmonhoc = newmonhoc;
                       OnPropertyChanged("Monhocs");
                   }
                   else if (e.Key == Key.D3 || e.Key == Key.NumPad3)
                   {
                       savemonhoc.Execute("Update");
                   }
                   else if (e.Key == Key.D4 || e.Key == Key.NumPad4)
                   {
                       // delete                    
                       savemonhoc.Execute("Delete");
                   }

                   else if (e.Key == Key.D2 || e.Key == Key.NumPad2)
                   {
                       InsertMonHoc();
                   }
               //if (e.Key == Key.D5) dg.CancelEdit();                               
           }
               
         //  else { dg.BeginEdit(); }
          // else
            //  if( e.Key==Key.F2) dg.BeginEdit();
        }               
        public void RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
        {
            //MessageBox.Show("su kien roweditend");
            DataGrid dg = (DataGrid)sender;
            int index = e.Row.GetIndex();
            string mamh = ((TextBlock)dg.Columns[1].GetCellContent(e.Row)).Text;
            if (mamh == "0") InsertMonHoc();
            else UpdateCurrentMonHoc();                                 
        }            
        #endregion
        public IList<MonHoc> Monhocs
        {
            get { return monhocs; }
            set
            {
                monhocs = value;
                this.OnPropertyChanged("Monhocs");                            
            }
        }
        private IList<MonHoc2> lstMh;
        public IList<MonHoc2> LstMh
        {
            get { return lstMh; }
            set { lstMh = value; OnPropertyChanged("LstMh"); }
        }           
        private MonHoc2 currentmh;

        public MonHoc2 Currentmh
        {
            get { return currentmh; }
            set { currentmh = value;
            OnPropertyChanged("Currentmh");
            }
        }
        private MonHoc currentmonhoc;
        public MonHoc Currentmonhoc
        {
            get { return this.currentmonhoc; }
            set
            {
                this.currentmonhoc = value;
                this.newmonhoc = this.currentmonhoc;
                this.OnPropertyChanged("Currentmonhoc");
                if (this.currentmonhoc == null) this.newmonhoc = new MonHoc();
                else { RefreshToViewErrors(); }
            }
        }
        void kiemtrahople()
        {
            this.Tenmh = Currentmonhoc.Tenmh;
            this.Hocphi = Currentmonhoc.Hocphi;
            this.Sotc = Currentmonhoc.Sotc;
        }        
        #region các phương thức contructor trong viewmodel
        public MonHocViewModel()
        {                        
            this.RefreshMonHoc();     ;           
            this.savemonhoc = new SaveCurrentMonhoc(this);                                  
            monhocclient.InsertMonHocCompleted += new EventHandler<InsertMonHocCompletedEventArgs>(monhocclient_InsertMonHocCompleted);
            monhocclient.UpdateMonHocCompleted +=new EventHandler<UpdateMonHocCompletedEventArgs>( monhocclient_UpdateMonHocCompleted);
            monhocclient.DeleteMonHocCompleted += new EventHandler<DeleteMonHocCompletedEventArgs>(monhocclient_DeleteMonHocCompleted);
        }
        public void RefreshMonHoc()
        {
            LstMh = new List<MonHoc2>();
            this.monhocclient.GetAllMonHocCompleted += (s, e) =>
            {
                this.monhocs = e.Result;
                OnPropertyChanged("Monhocs");
                Monhocs.Insert(0,new MonHoc());                
            };
            this.monhocclient.GetAllMonHocAsync();
            IsNew = false;   
        }
        #endregion

        MonHoc2 mh2;
        public MonHoc2 Mh2
        {
            get { return mh2; }
            set { 
                mh2 = value;
                OnPropertyChanged("Mh2");
            }
        }

        #region Data fields
        
        private MonHoc newmonhoc = new MonHoc();      
        private const string TenmhProperty = "Tenmh";
        public string Tenmh
        {
            get { return newmonhoc.Tenmh; }
            set
            {
                this.newmonhoc.Tenmh = value;               
                OnPropertyChanged(TenmhProperty);// bao de ben view biet doi tuong da thay doi
                ClearError(TenmhProperty);// xoa cac loi truoc do de chuan bi kiem tra hop le
                // ham kiem tra hop le... o day
                var validationResult = validator.Validate(this.newmonhoc, TenmhProperty);
                if (!validationResult.IsValid)
                    validationResult.Errors.ToList().ForEach(x => SetError(TenmhProperty, x.ErrorMessage));
            }
        }
        private const string SotcProperty = "Sotc";
        private int sotc;        
        public int? Sotc
        {
            get { return this.newmonhoc.Sotc; }
            set
            {
                //  this.newmonhoc.sotc = value;
                this.newmonhoc.Sotc = value;                 
                OnPropertyChanged(SotcProperty);
                ClearError(SotcProperty);
                var validationResult = validator.Validate(this.newmonhoc, SotcProperty);
                if (!validationResult.IsValid)
                    validationResult.Errors.ToList().ForEach(x => SetError(SotcProperty, x.ErrorMessage));
            }
        }
        private const string HocphiProperty = "Hocphi";
        private int hocphi;
        public int? Hocphi
        {
            get { return newmonhoc.Hocphi; }
            set { 
                //hocphi = value;
                this.newmonhoc.Hocphi = value;
                OnPropertyChanged(HocphiProperty);
                ClearError(HocphiProperty);
                var validationResult = validator.Validate(this.newmonhoc, HocphiProperty);
                if (!validationResult.IsValid)
                    validationResult.Errors.ToList().ForEach(x => SetError(HocphiProperty, x.ErrorMessage));
            }
        }
        #endregion
        private SaveCurrentMonhoc savemonhoc;
        public SaveCurrentMonhoc Savemonhoc
        {
            get { return this.savemonhoc; }
            set
            {
                this.savemonhoc = value;
                OnPropertyChanged("Savemonhoc");
            }            
        }
        private void ResetDataFiels()
        {           
            this.OnPropertyChanged("Currentmonhoc");
            this.OnPropertyChanged("Mamh");
            this.OnPropertyChanged("Tenmh");
            this.OnPropertyChanged("Sotc");
            this.OnPropertyChanged("Hocphi");
        } 
        #region thao tác với csdl
        void monhocclient_UpdateMonHocCompleted(object sender, UpdateMonHocCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.Message = "Update" + e.Result;
            }
            else
            {
                this.Message = "Update " + e.Result;
                MessageBox.Show("update");
            }
        }
        private void UpdateCurrentMonHoc()
        {
            RefreshToViewErrors();
            if (!HasErrors)
            {                
                this.monhocclient.UpdateMonHocAsync(Currentmonhoc);               
            }
        }
        void monhocclient_DeleteMonHocCompleted(object sender, DeleteMonHocCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.Message = "Delete " + e.Result;
            }
            else
            {
                this.Message = "Delete " + e.Result;
                Monhocs.Remove(Currentmonhoc);
            }
        }
        private void DeleteMonHoc()
        {
            if (Currentmonhoc.Mamh == 0) { Message = "Khong the xoa dong nay"; return; }

            RefreshToViewErrors();
            if (!this.HasErrors)
            {               
                monhocclient.DeleteMonHocAsync(currentmonhoc.Mamh.ToString());                               
            }           
        }        
        void monhocclient_InsertMonHocCompleted(object sender, InsertMonHocCompletedEventArgs e)
        {
            if (e.Error != null) { MessageBox.Show("Loi"); Currentmonhoc = Monhocs[0]; }
            else
            {
                MessageBox.Show("insert");
                this.Message = "Insert " + e.Result;
                Monhocs.Add(e.info);
                Currentmonhoc = e.info;
                Monhocs[0] = new MonHoc();
                OnPropertyChanged("Monhocs");
            }
        }
        private void InsertMonHoc()
        {            
            RefreshToViewErrors();
            if (!this.HasErrors)
            {                
                monhocclient.InsertMonHocAsync(newmonhoc);                               
            }            
        }
        private void XuatReport()
        {
            // MonHoc m = new MonHoc();
            UrlReport para = new UrlReport { personCreate = PersonCreate };
            HtmlPage.Window.Invoke("showPopupReport", new string[] { para.ToString() });
        }
        public class UrlReport
        {
            public string personCreate { get; set; }


            /// <summary>
            /// Override ToString so we can easily return our
            /// URL Parameters
            /// </summary>
            /// <returns></returns>
            public override string ToString()
            {
                return string.Format("?personCreate={0}", personCreate);
            }
        }
        #endregion 
        private string personCreate;

        public string PersonCreate
        {
            get { return personCreate; }
            set
            {
                personCreate = value;
                OnPropertyChanged("PersonCreate");
            }
        }
        private string message;
        public string Message
        {
            get { return message; }
            set
            {
                message = value;
                OnPropertyChanged("Message");
            }
        }

        private void RefreshToViewErrors()
        {
            this.Tenmh = this.newmonhoc.Tenmh;
            this.Sotc = this.newmonhoc.Sotc;
            this.Hocphi = this.newmonhoc.Hocphi;
            
        }
        
        public class SaveCurrentMonhoc : ICommand
        {
            private MonHocViewModel viewmodel;
            public SaveCurrentMonhoc(MonHocViewModel viewmodel)
            {
                this.viewmodel = viewmodel;
                this.viewmodel.PropertyChanged += (s, e) =>
                {
                    if (this.CanExecuteChanged != null)
                    {
                        this.CanExecuteChanged(this, new EventArgs());
                    }
                };
                // this.viewmodel.UpdateCurrentMonHoc();
            }
            public bool CanExecute(object parameter)
            {
                if (parameter.ToString() == "Insert")
                    return true;
                else
                    return this.viewmodel.Currentmonhoc != null;
            }

            public event EventHandler CanExecuteChanged;
            public void Execute(object parameter)
            {
                switch (parameter.ToString())
                {
                    case "Update": this.viewmodel.UpdateCurrentMonHoc();
                        break;
                    case "Delete": this.viewmodel.DeleteMonHoc();
                        break;
                    case "Insert": this.viewmodel.InsertMonHoc(); 
                        break;
                    case "Report": this.viewmodel.XuatReport();
                        break;
                    default: break;
                }
            }            
        }
        
        public class MonHoc2:ViewModelBase
        {
            public int ID { get; set; }
            int? mamh1;

            public int? Mamh1
            {
                get { return mamh1; }
                set { mamh1 = value; OnPropertyChanged("Mamh1"); }
            }
            string tenmh1;

            public string Tenmh1
            {
                get { return tenmh1; }
                set { tenmh1 = value; OnPropertyChanged("Tenmh1"); }
            }
            int? sotc1;

            public int? Sotc1
            {
                get { return sotc1; }
                set { sotc1 = value; OnPropertyChanged("Sotc1"); }
            }
            int? hocphi1;

            public int? Hocphi1
            {
                get { return hocphi1; }
                set { hocphi1 = value; OnPropertyChanged("Hocphi1"); }
            }
            public MonHoc2()
            {
                Sotc1 = null;
                Hocphi1 = null;
            }
            public MonHoc2(MonHoc mh)
            {
                this.Mamh1 = mh.Mamh;
                this.Tenmh1 = mh.Tenmh;
                this.Sotc1 = mh.Sotc;
                this.Hocphi1 = mh.Hocphi;
            }
        }
    }
}
       